package com.hdhere.core.http.session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * Java Serialization Redis serializer. Delegates to the default (Java based) serializer in Spring 3.
 *
 * @author Mark Pollack
 * @author Costin Leau
 */
public class MyJdkSerializationRedisSerializer implements RedisSerializer<Object> {

    private static final Logger logger = LoggerFactory.getLogger(MyJdkSerializationRedisSerializer.class);

    static final byte[] EMPTY_ARRAY = new byte[0];

    static boolean isEmpty(byte[] data) {

        return ( data == null || data.length == 0 );
    }

    private Converter<Object, byte[]> serializer = new SerializingConverter();
    private Converter<byte[], Object> deserializer = new DeserializingConverter();

    public Object deserialize(byte[] bytes) {

        if (isEmpty(bytes)) {
            return null;
        }

        try {
            return deserializer.convert(bytes);
        }
        catch (Exception ex) {
            // logger.warn("Cannot deserialize", ex);
            return null;
			/* throw new SerializationException("Cannot deserialize", ex); */
        }
    }

    public byte[] serialize(Object object) {

        if (object == null) {
            return EMPTY_ARRAY;
        }
        try {
            return serializer.convert(object);
        }
        catch (Exception ex) {
            throw new SerializationException("Cannot serialize", ex);
        }
    }
}
